<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    use SoftDeletes;

    use Relations\ImUserHasNotice,
        Relations\ImUserHasWay,
        Relations\ImUserHasCurrent;
    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'nickname',
        'email',
        'password',
        'im_number',
        'headimg',
        'phone'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * 关联消息设置
     * @param
     * @return
     */
    public function notice()
    {
        return $this->belongsTo(ImUserNoticeStatus::class, 'id', 'user_id');
    }

    /**
     * 关联我的隐私设置
     * @param
     * @return
     */
    public function secrecy()
    {
        return $this->belongsTo(ImUserWay::class, 'id', 'user_id');
    }

    //省份关联
    public function province()
    {
        return $this->hasOne(ImProvince::class,'province_id','province_id');
    }

    //城市关联
    public function city()
    {
        return $this->hasOne(ImCity::class,'city_id','city_id');
    }

    //区域关联
    public function area()
    {
        return $this->hasOne(ImArea::class,'area_id','area_id');
    }

    /**
     * @desc 删除用户
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function delUserAccount($userId = 0)
    {
        $user = $this->where(['id' => $userId])->first();
        if (!$user)
        {
            return ['code' => 1, 'msg' => '删除失败'];
        }

        $user->delete();

        return ['code' => 0, 'msg' => '删除成功'];
    }

    /**
     * @desc 通过手机号获取uid，昵称，头像
     * @param array $phone 手机号数组
     * @return array
     * @author zhouzhou
     * @time 2021/12/1 11:21
     */
    public function getUserByPhone($phone)
    {
        if (empty($phone))
        {
            return [];
        }

        $query = $this->whereIn('phone', $phone);
        $list = $query->select('id','nickname','phone','im_number','headimg')
            ->get()->toArray();
        if ($list)
        {
            return $list;
        }

        return [];
    }

    /**
     * @desc 通过uid获取昵称和头像
     * @param array $uids uid数组
     * @return array
     * @author zhouzhou
     * @time 2021/12/1 11:21
     */
    public function getUserByIds($uids)
    {
        if (empty($uids))
        {
            return [];
        }

        $query = $this->whereIn('id', $uids);
        $list = $query->select('id','nickname','phone','im_number','headimg')
            ->get()->toArray();
        if ($list)
        {
            return $list;
        }

        return [];
    }

    /**
     * @desc 点击搜索
     * @param int $limit
     * @param int $offset
     * @param int $userId
     * @param string $search
     * @return mixed
     * @author zhouzhou
     * @time 2021/12/2 14:27
     */
    public function searchList($limit, $offset, $search, $userId)
    {
        // 查询我所有的好友
        $imUserFriend = new ImUserFriend();
        $userFriendList = $imUserFriend->getUserFriednByUid($userId);
        $userFriendList = array_column($userFriendList, null, 'other_uid');

        $userList = $this->when($search, function ($query) use ($search) {
            return $query->where('phone', 'like', '%'.$search.'%')->orWhere('im_number', 'like', '%'.$search.'%');
        })->select('id','phone','im_number','headimg','sex','phone','nickname')->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        foreach ($userList as $key =>&$val)
        {
            $val['friend_status'] = !empty($userFriendList[$val['id']]) ? 1 : 0; // 1已添加好友 0未添加好友
        }

        return $userList;
    }

    /**
     * @desc 用户个人资料修改
     * @param array $input 传过来数组对象
     * @param array $user 用户对象
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function editInfo($input,  $user)
    {
        $type = $input['type'];
        $value = $input['value'];
        switch($type)
        {
            case ($type =='headimg'):  // 头像
                $user->$type = $value;
                break;
            case ($type =='nickname'):  // 昵称
                $user->$type = $value;
                break;
            case ($type =='sex'):  // 性别
                $user->$type = $value;
                break;
            case ($type =='signature'):  // 个性签名
                $user->personalized_signature = $value;
                break;
            case ($type =='area'):  // 地区
                $user->province_id = $input['province_id'] ?? 0;
                $user->city_id = $input['city_id'] ?? 0;
                $user->area_id = $input['area_id'] ?? 0;
                $user->address = $value ?? ''; // 详情地址
                break;
            default :
                $user->$type = $value;
                break;
        }

        if($user->save() == FALSE)
        {
            return ['code' => 1, 'msg' => '修改失败'];
        }

        return ['code' => 0, 'id' => $this->id, 'msg' => '修改成功'];
    }
}
